﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CanDoo.Core;

using CanDoo.Core.Data;
using CanDoo;
using CanDoo.Data;
using CanDoo.Extensions;

using CanDoo.Admin.Core.Contracts;
using CanDoo.Admin.Core.Models;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Oil.Core.Models;
using Mehdime.Entity;
using System.Data.Entity;
using System.Linq.Expressions;

namespace CanDoo.Oil.Core.Services 
{
    /// <summary>
    /// 业务实现——文档附件
    /// </summary>
    public class AdministratorService : CanDoo.Data.Entity.Services.ServiceBase<Administrator>, IAdministratorContract, CanDoo.Core.Dependency.IScopeDependency
    {
        //TODO : 这里要不要改为 OnDelete事件
        public IUserContract UserContract { get; set; }
        public override OperationResult DeleteEntity(Administrator Entity)
        {
            OperationResult result;
            using (var scope = DbScopeFactory.Create())
            {
                Delete(Entity);
                UserContract.Delete(Entity.Id);
                result = scope.SaveChanges() > 0
                ? new OperationResult(OperationResultType.Success, "数据删除成功!")
                : new OperationResult(OperationResultType.NoChanged);
            }
            //if (result.Succeeded && OnChanged != null)
            //    OnChanged();
            return result;
        }

        public override OperationResult DeleteEntity(IEnumerable<Administrator> Entities)
        {
            OperationResult result;
            using (var scope = DbScopeFactory.Create())
            {
                Delete(Entities);
                foreach(var m in Entities)
                    UserContract.Delete(m.Id);
                result = scope.SaveChanges() > 0
                ? new OperationResult(OperationResultType.Success, "数据删除成功!")
                : new OperationResult(OperationResultType.NoChanged);
            }
            //if (result.Succeeded && OnChanged != null)
            //    OnChanged();
            return result;
        }

        public override OperationResult DeleteEntity(Expression<Func<Administrator, bool>> predicate)
        {
            var mList = Entities.Where(predicate).ToList();
            return DeleteEntity(mList);
        }

        public override OperationResult DeleteEntity(long id)
        {
            OperationResult result;
            using (var scope = DbScopeFactory.Create())
            {
                Delete(id);
                UserContract.Delete(id);
                result = scope.SaveChanges() > 0
                ? new OperationResult(OperationResultType.Success, "数据删除成功!")
                : new OperationResult(OperationResultType.NoChanged);
            }
            //if (result.Succeeded && OnChanged != null)
            //    OnChanged();
            return result;
        }
    }
}
